package cn.mymall.web.controller.houtai.mall;

import cn.mymall.entity.mall.Shipper;
import cn.mymall.service.mall.IShipperService;
import cn.mymall.support.ResultCode;
import cn.mymall.util.BaseWebUtil;
import cn.mymall.util.BindUtils;
import cn.mymall.util.DateUtil;
import cn.mymall.web.controller.houtai.BaseHoutaiController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class ShipperApiController extends BaseHoutaiController {
    @Autowired
    private IShipperService shipperService;

    // 列表
    @RequestMapping("/api/shipper/list")
    public ResultCode<Map> list(Integer pagenum, Integer pagesize, String name) {
        if (pagenum == null) {
            pagenum = 1;
        }
        if (pagesize == null) {
            pagesize = 10;
        }
        Page<Shipper> page = new Page(pagenum, pagesize);
        QueryWrapper<Shipper> qw = new QueryWrapper();
        if(StringUtils.isNotBlank(name)){
            qw.like("name", name);
        }
        IPage<Shipper> ipage = shipperService.page(page, qw.orderByDesc("id"));
        Map map = new HashMap<>();
        map.put("shipperList", ipage.getRecords());
        map.put("page", ImmutableMap.of("total", page.getTotal(), "pagenum", page.getCurrent()));
        return ResultCode.getSuccessReturn(map);
    }

    // 新增or修改
    @RequestMapping("/api/shipper/get")
    public ResultCode<Shipper> get(Integer id) {
        Shipper shipper = new Shipper();
        if (id != null) {
            shipper = shipperService.getById(id);
        }
        return ResultCode.getSuccessReturn(shipper);
    }

    // 保存
    @RequestMapping("/api/shipper/save")
    public ResultCode save(Integer id) {
        Shipper shipper = null;
        if (id != null) {
            shipper = shipperService.getById(id);
        } else {
            shipper = new Shipper();
            shipper.setAddTime(DateUtil.getCurFullTimestamp());
        }
        BindUtils.bindData(shipper, BaseWebUtil.getRequestParams());
        if (StringUtils.isBlank(shipper.getName())) {
            return ResultCode.getFailure("请输入名称");
        }
        shipper.setUpdateTime(DateUtil.getCurFullTimestamp());
        shipperService.saveOrUpdate(shipper);
        return ResultCode.SUCCESS;
    }
}
